package com.example.demo.service;

/**
 * @ClassName ResinLncrService
 * @Description
 * @Author 51
 * @Date 2020年3月17日 下午2:10:00
 */

import org.redisson.api.RCountDownLatch;
import org.redisson.api.RLock;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
public class ResinLncrService {

    @Resource
    RedissonClient redis;

    @Resource
    StringRedisTemplate stringRedisTemplate;

    /**
     * 分布式锁的应用
     */
    public void useRedissonForlockWithRedisson() {
        RLock lock = redis.getLock("lock");
        // 业务demo
        try {
            // 感知别人删锁|阻塞锁
            lock.lock(3, TimeUnit.SECONDS);// 过期自动解锁
            incrDemo();
        } finally {
            lock.unlock();
        }
    }

    /**
     * 无锁
     */
    public void incrnolock() {
        // 业务demo
        incrDemo();
    }

    /**
     * 单机可以|分布式不行
     */
    public synchronized void incrSyncLock() {
        // 业务demo
        incrDemo();
    }

    /**
     * 单机没有 出现问题(因为是原子操作)|
     */
    public void incre() {
        ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
        Long num = opsForValue.increment("num");
    }

    private void incrDemo() {
        ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
        String num1 = opsForValue.get("num");
        if (num1 != null) {
            int i = Integer.parseInt(num1);
            opsForValue.set("num", String.valueOf(i + 1));
            System.out.println("num is " + num1);
        }
    }
    /**
     * ---------信号量--------------------------
     */
    /***
     * 信号量
     * @return
     */
    public boolean tc() throws InterruptedException {
        RSemaphore redisSemaphore = redis.getSemaphore("tcc");
        redisSemaphore.acquire();
        return true;
    }

    public boolean rc() throws InterruptedException {
        RSemaphore redisSemaphore = redis.getSemaphore("tcc");
        redisSemaphore.release(10);
        return true;
    }

    //
    public Boolean gogogo() {
        RCountDownLatch nums = redis.getCountDownLatch("nums");
        nums.countDown();
        System.out.println("溜了溜了");
        return true;
    }

    public Boolean lockDoor() throws InterruptedException {

        RCountDownLatch nums = redis.getCountDownLatch("nums");
        nums.await();
        return true;
    }
}
